package com.base.pub.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.dragonnova.business.common.Constants;
import org.dragonnova.business.model.User;
import org.dragonnova.business.service.UserService;
//import org.dragonnova.business.util.AppConfigPropertyHelper;
import org.dragonnova.business.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.base.pub.config.GlobalConfig;
import com.base.pub.util.TokenUtils;

public class MobileInterceptor extends BaseController implements
		HandlerInterceptor {
	@Autowired
	private UserService userService;

	private List<String> whiteUrls;

	@Autowired
	public void setWhiteUrls(List<String> whiteUrls) {
		this.whiteUrls = whiteUrls;
	}

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		String requestURI = request.getServletPath().trim();
		if (this.whiteUrls.contains(requestURI)) {
			return true;
		}

		if (!requestURI.equals("/") && isLogin(request, response)) {
			return true;
		}
		gotoPage(request, response, "/login.html");
		return false;
	}

	private boolean isLogin(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String token = TokenUtils.getToken(request);
		if (StringUtils.isEmpty(token))
			return false;

		String userName = TokenUtils.getValue(token, "userName");
		String sign = TokenUtils.getValue(token, "sign");
		if (!StringUtils.isEmpty(userName)) {
			try {
				Boolean tokenSave = (Boolean) request.getSession()
						.getAttribute(Constants.VALIDATE_SESSION_TOKEN);
				if (tokenSave == null || !tokenSave)
					throw new SessionTimeoutException("会话超时.");

				User user = userService.getUserByName(userName);
				if (user != null
						&& sign.equals(DigestUtils.md5DigestAsHex(user
								.getPassword().getBytes()))) {
					return true;
				}
			} catch (Exception e) {
				throw e;
			}
		}
		return false;
	}

	private void gotoPage(HttpServletRequest request,
			HttpServletResponse response, String pageName) {
		String loginUrl = request.getContextPath();
		loginUrl += pageName;
		try {
			// response.sendRedirect(loginUrl);
			request.getRequestDispatcher(pageName).forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

		if (modelAndView != null) {
			modelAndView.addObject("theme",
					GlobalConfig.getConfig("sysconf.theme"));
			modelAndView.addObject("ctx", request.getContextPath());
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
